package com.example.qihuibao.utils;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Decoder;
import Decoder.BASE64Encoder;

/**
 * 3DES加密解密
 */
public class DES3Util {
    //密钥分为两种：初始化密钥，与开发商相关；企业密钥，与企业相关
    public final static String KEY = "iM/lCJpec84GEA768Y2NSojP5QiaXnPO";
    public static String encroptMode = "ECB";
    public static String paddingMode = "PKCS5Padding";
    public static String algorithm = "DESede";
    public static String charset = "UTF-8";

    /**
     * 加密
     */
    public static String EncryptData(String oriData, String keyStr) {
        try {
            BASE64Decoder base64decoder = new BASE64Decoder();
            BASE64Encoder base64encoder = new BASE64Encoder();
            byte[] keyBytes = base64decoder.decodeBuffer(keyStr);
            SecretKey key = new SecretKeySpec(keyBytes, algorithm);
            Cipher cipher = Cipher.getInstance(algorithm + "/" + encroptMode + "/" + paddingMode);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptBytes = cipher.doFinal(oriData.getBytes(charset));
            return base64encoder.encode(encryptBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 解密
     */
    public static String DecryptData(String encData, String keyStr) {
        try {
            BASE64Decoder base64decoder = new BASE64Decoder();
            byte[] keyBytes = base64decoder.decodeBuffer(keyStr);
            SecretKey key = new SecretKeySpec(keyBytes, algorithm);
            Cipher cipher = Cipher.getInstance(algorithm + "/" + encroptMode + "/" + paddingMode);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decBytes = cipher.doFinal(base64decoder.decodeBuffer(encData));
            return new String(decBytes, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}
